#include <string>
#include <vector>

using namespace std;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
class Solution
{
public:
    bool dfs(vector<vector<char>> &board, const string &word, int x, int y, int k)
    {
        if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size() || board[x][y] != word[k])
        {
            return false;
        }

        if (k == word.size() - 1)
        {
            return true;
        }

        board[x][y] = '\0';
        bool ret = false;
        for (int i = 0; i < 4; ++i)
        {
            if (dfs(board, word, x + dx[i], y + dy[i], k + 1))
            {
                ret = true;
                break;
            }
        }
        board[x][y] = word[k];
        return ret;
    }
    bool exist(vector<vector<char>> &board, string word)
    {
        for (int i = 0; i < board.size(); ++i)
        {
            for (int j = 0; j < board[i].size(); ++j)
            {
                if (dfs(board, word, i, j, 0))
                {
                    return true;
                }
            }
        }
        return false;
    }
};